define(function (require, exports, module) {
    require("apps/process/page.css");
    require("fancybox/jquery.fancybox.css");
    require("fancybox/jquery.fancybox");
    require("apps/file");
    exports.init = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("begin").datetimebox();
        page.getJqDom("end").datetimebox();
        page.getJqDom("attachment").fileupload({
            selectText:"选择数据文件",
            uploader: ctx + '/app/api/file/uploadTempFile',
            fileTypeDesc: '*.xls;*.xlsx;*.csv;*.dat;*.bmp;*.mdb;',
            fileTypeExts: '*.xls;*.xlsx;*.csv;*.dat;*.bmp;*.mdb;',
            onUploadSuccess: function (files) {
                var file = files[0];
                page.getJqDom("fileMessage").show();
                $('<div data-path="' + file.href + '" style="overflow:hidden">' +
                    '<i class="fa fa-trash fa-lg fa-lg" style="float: right;position: relative;top: 10px;margin-right: 10px;font-size: 20px;cursor: pointer">' +
                    '</i>' + file.fileHtml + '</div>').appendTo(page.getJqDom("fileMessage"))
                    .find("i.fa-trash").on("click", function () {
                        $(this).parent().fadeOut(function () {
                            $(this).remove();
                            var _path = [];
                            page.getJqDom("fileMessage").children().each(function () {
                                _path.push($(this).attr("data-path"));
                            });
                            page.getJqDom("filePath").val(_path.join(","));
                        })
                    });
                var _path2 = [];
                page.getJqDom("fileMessage").children().each(function () {
                    _path2.push($(this).attr("data-path"));
                });
                page.getJqDom("filePath").val(_path2.join(","));
                page.getJqDom("fileMessage").children().children().css({border: "none"});
            }
        });

        function doParse(random, startTime, endTime, filePath, listener) {
            $.post(ctx + "/app/api/lab/parse", {
                code: config.code,
                startTime: startTime,
                endTime: endTime,
                filePath: filePath,
                random: random
            }, function (data) {
                if ($.isPlainObject(data) && data.error) {
                    $.messager.alert('信息',
                        data.msg, 'info');
                    $("body").wait("end");
                } else {
                    if (data.status == 'FAILURE') {
                        listener.failure(data);
                    } else if (["SUCCESS_LOAD_DATA", "SUCCESS_DRAW"].contains(data.status)) {
                        $("body").wait("start", "数据抓取成功，等待数据渲染");
                        page.getJqDom("grant").hide();
                        listener.success(data);
                        $("body").wait("end");
                    } else {
                        setTimeout(function () {
                            doParse(random, startTime, endTime, true, filePath, listener);
                        }, 1000 * 10);
                    }
                }
            }, "JSON");
        }

        var template = '{{#.}}<dl class="grant-img"><dt>' +
            '<a data-id="facy" href="' + ctx + '/print/{{path}}" title="{{title}}">' +
            '<img style="width: 120px;height: 80px;" alt="" src="' + ctx + '/print/{{path}}" /></a>' +
            '</dt><dd><span class="title">{{_title}}</span></dd>' +
            '</dl>{{/.}}';

        function renderLine(dom, json) {
            var ec = require("echarts/echarts");
            var themes = require("echarts/theme/gray");
            require("zrender/zrender");
            var serieData = [], titles = [], times = json.times;
            for (var i in json.data) {
                serieData.push({
                    name: i,
                    type: "line",
                    data: json.data[i]
                });
                titles.push({
                    name: i,
                    textStyle: {
                        fontSize: 12
                    }
                });
            }

            var option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: "horizontal",
                    data: titles
                },
                dataZoom: {
                    show: true,
                    start: 0,
                    end: 100,
                    y: 460
                },
                grid: {
                    y: 120,
                    y2: 80
                },
                calculable: false,
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: times
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: serieData
            };

            var myChart = ec.init(dom);
            myChart.setOption(option);
        }


        function doGetParseJson(experimentalDataPath, hasChart) {
            $.getJSON(ctx + "/print/" + experimentalDataPath + "/data.json", function (data) {
                if ($.isPlainObject(data) && data.error) {
                    $.messager.alert('信息',
                        data.msg, 'info');
                } else {
                    var labels = data.labels, labelHtm = [];
                    if (labels && labels.length) {
                        var labelHolder = $("<div class='label-holder'></div>").appendTo(page.getJqDom("data"));
                        for (var i = 0, l = labels.length; i < l; i++) {
                            if (labels[i].type == "LABEL_TYPE_IMG") {
                                var uuid = $.utils.createUUID(6);
                                var path = ctx + "/print" + labels[i].text;
                                labelHtm.push('<a data-id="viewimg" href="' + path + '"><img src="' + path + '" style="width: 60px;height: 30px;"/></a>');
                            } else {
                                labelHtm.push("<span>" + labels[i].text + "<span>");
                            }
                        }
                        labelHolder.html(labelHtm.join("")).children("a[data-id=viewimg]").each(function () {
                            $(this).fancybox();
                        });
                    }
                    if(hasChart){
                        var l = data.times.length * 10, ll = 0;
                        for (var i in data.data){
                            ll++;
                        }
                        ll = (ll / 4) * 200;
                        l = l < 1400 ? 1400 : l;
                        l = l > 3000 ? 3000 : l;
                        l = l < ll ? ll : l;

                        var id = $.utils.createUUID(6);
                        page.getJqDom("data").append("<a data-id='view' href='#" + id + "' iconCls='fa fa-eye fa-lg'>查看实验数据图</a><div style='display: none;'><div style='overflow-x: auto;overflow-y:hidden'>" +
                            "<div id='" + id + "'></div></div></div>").find("a[data-id=view]").linkbutton().eq(0).fancybox({
                            fitToView: true
                        });
                        $("#" + id).css({
                            width: l,
                            height: 500
                        });
                        renderLine(document.getElementById(id), data);
                    }
                    $("<a data-id='download' " +
                        "href=\""+ ctx +"/download/"+ experimentalDataPath +"/data.xls\" " +
                        "class='ml10' href='#"+ id +"' iconCls='fa fa-download fa-lg'>下载实验数据</a>").appendTo(page.getJqDom("data")).linkbutton();
                    $("body").wait("end");
                }
            }, "JSON")
        }

        var errorDes = {
            FILE_NOT_FOUND: "带解析路径的实验文件不存在，请检查文件路径是否正确，重新进行数据抓取！",
            DATA_NOT_FOUND: "制定时间的数据未能在目标实验文件中找到数据，请调整实验时间，重新抓取数据！",
            PARSE_EXCEPTION: "服务器异常导致的数据抓取失败，请联系系统管理员进行排查！"
        };
        page.getJqDom("grant").linkbutton({
            onClick: function () {
                filePath = page.getJqDom("filePath").val();
                if(!filePath || !filePath.length){
                    $.messager.alert("信息", "请上传实验数据文件");
                    return;
                }
                $("body").wait("start", "开始进行数据抓取，请等待系统返回结果！");
                var start = page.getJqDom("begin").datetimebox("getValue"),
                    end = page.getJqDom("end").datetimebox("getValue"),
                    filePath = page.getJqDom("filePath").val();
                doParse(new Date().getTime(), start, end, filePath, {
                    success: function (data) {
                        //获取json的路径，进行数据解析
                        page.getJqDom("experimentalData").val(data.id);
                        doGetParseJson(data.experimentalDataPath, data.hasChart);
                        $("body").wait("end");
                    },
                    failure: function (data) {
                        $.messager.alert("信息", "数据采集失败，失败原因“" + errorDes[data.failureMsg] + "”");
                        $("body").wait("end");
                    }
                })
            }
        })
    }
});